package com.szp.lagou.oss.aliyun.service;

import com.aliyun.oss.OSSClient;
import com.szp.lagou.oss.aliyun.bean.ResponseResult;
import com.szp.lagou.oss.aliyun.bean.ResultCode;
import com.szp.lagou.oss.aliyun.config.AliyunConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class AliyunOssService {
    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{"jpg", "jpeg", "png"};

    public ResponseResult upload(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        long size = multipartFile.getSize();
        if (size > 5 * 1024 * 1024) {
            return new ResponseResult(ResultCode.VALIDATE_FAILED.getCode(), "上传文件过大，不能超过5M");
        }

        if (!StringUtils.containsAny(ext, IMAGE_TYPE)) {
            return new ResponseResult(ResultCode.VALIDATE_FAILED.getCode(), "文件类型错误，应为jpg,jpeg,png");
        }
        String key = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))
                + RandomStringUtils.randomNumeric(6) + "." + ext;

        String data = "http://" + aliyunConfig.getBucketName() + "." + aliyunConfig.getEndpoint() + "/" + key;
        try {
            this.ossClient.putObject(aliyunConfig.getBucketName(), key, new ByteArrayInputStream(multipartFile.getBytes()));
            return ResponseResult.ok(data);
        } catch (Exception e) {
            return ResponseResult.fail(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
        }
    }

    public ResponseEntity download(String url) {
        try {
            InputStream stream = this.ossClient.getObject(aliyunConfig.getBucketName(), url).getObjectContent();
            return ResponseEntity.status(HttpStatus.CREATED).contentType(MediaType.IMAGE_PNG)
                    .body(new InputStreamResource(stream));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).contentType(MediaType.TEXT_HTML)
                    .body("下载失败");
        }
    }

    public ResponseResult delete(String url) {
        this.ossClient.deleteObject(aliyunConfig.getBucketName(), url);
        return ResponseResult.ok("删除成功");

    }
}
